﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace CPPEI.ETL.TaskAgent.HttpClient
{
    class Http
    {
        public delegate string Post2ServerEventHandler(string url, Dictionary<string, string> parameters);

        public static void TestPostToServer()
        {
            string url = string.Format("{0}Api.ashx", CPPEI.ETL.TaskAgent.Cache.WebBaseAddress);
            Dictionary<string, string> parameters = new Dictionary<string, string>();
            parameters.Add("sys:sno", "ETL");
            parameters.Add("sys:act", "InvokeTask");
            parameters.Add("TaskId", Guid.Empty.ToString());
            parameters.Add("ServiceId", Guid.Empty.ToString());
            parameters.Add("SourceId", Guid.Empty.ToString());
            parameters.Add("Key", CPPEI.ETL.TaskAgent.Cache.Key.ToString());

            //Logger.InfoToTag(Library.LogTAG, string.Format("TestToServer:{0}", url));

            Post2ServerEventHandler method = PostNoLog;
            method.BeginInvoke(url, parameters, OnAsyncCallback, method);
        }

        public static void PostToServer(CPPEI.ETL.Domain.TaskProxy.Task task)
        {
            string url = string.Format("{0}Api.ashx", CPPEI.ETL.TaskAgent.Cache.WebBaseAddress);
            Dictionary<string, string> parameters = new Dictionary<string, string>();
            parameters.Add("sys:sno", "ETL");
            parameters.Add("sys:act", "InvokeTask");
            parameters.Add("TaskId", task.Id.ToString());
            parameters.Add("ServiceId", task.ServiceId.ToString());
            parameters.Add("SourceId", task.SourceId.ToString());
            parameters.Add("Key", CPPEI.ETL.TaskAgent.Cache.Key.ToString());

            Logger.InfoToTag(Library.LogTAG, string.Format("PostToServer:{0},taskId:{1}", url, task.Id));

            Post2ServerEventHandler method = Post;
            method.BeginInvoke(url, parameters, OnAsyncCallback, method);
        }

        private static void OnAsyncCallback(IAsyncResult ar)
        {
            Post2ServerEventHandler method = ar.AsyncState as Post2ServerEventHandler;
            method.EndInvoke(ar);
        }

        public static string Post(string url, Dictionary<string, string> parameters)
        {
            StringBuilder requestUrl = new StringBuilder(url);

            StringBuilder postDataStringBuilder = new StringBuilder();
            foreach (string key in parameters.Keys)
            {
                string encodeData = System.Web.HttpUtility.UrlEncode(parameters[key]);
                postDataStringBuilder.AppendFormat("{0}={1}&", key, encodeData);
            }
            string postDataString = postDataStringBuilder.ToString();

            Logger.InfoToTag(Library.LogTAG, string.Format("Post:{0};data:{1}", url, postDataString));
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUrl.ToString());

            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] b = encoding.GetBytes(postDataString);
            request.UserAgent = "Mozilla/4.0";
            request.Method = "POST";
            //request.CookieContainer = _cookieContainer;
            request.ContentLength = b.Length;
            request.ContentType = "application/x-www-form-urlencoded";

            try
            {
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(b, 0, b.Length);
                }

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                string content = string.Empty;
                using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
                {
                    content = streamReader.ReadToEnd();
                }

                Logger.InfoToTag(Library.LogTAG, string.Format("Post:{0};data:{1};return:{2}", url, postDataString, content));
                return content;
            }
            catch(Exception ex)
            {
                Logger.ErrorToTag(Library.LogTAG, string.Format("发送请求失败,ex:{0}", ex));

                return string.Empty;
            }
        }

        public static string PostNoLog(string url, Dictionary<string, string> parameters)
        {
            StringBuilder requestUrl = new StringBuilder(url);

            StringBuilder postDataStringBuilder = new StringBuilder();
            foreach (string key in parameters.Keys)
            {
                string encodeData = System.Web.HttpUtility.UrlEncode(parameters[key]);
                postDataStringBuilder.AppendFormat("{0}={1}&", key, encodeData);
            }
            string postDataString = postDataStringBuilder.ToString();

            //Logger.InfoToTag(Library.LogTAG, string.Format("Post:{0};data:{1}", url, postDataString));
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUrl.ToString());

            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] b = encoding.GetBytes(postDataString);
            request.UserAgent = "Mozilla/4.0";
            request.Method = "POST";
            //request.CookieContainer = _cookieContainer;
            request.ContentLength = b.Length;
            request.ContentType = "application/x-www-form-urlencoded";

            try
            {
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(b, 0, b.Length);
                }

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                string content = string.Empty;
                using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
                {
                    content = streamReader.ReadToEnd();
                }

                //Logger.InfoToTag(Library.LogTAG, string.Format("Post:{0};data:{1};return:{2}", url, postDataString, content));
                return content;
            }
            catch (Exception ex)
            {
                //Logger.ErrorToTag(Library.LogTAG, string.Format("发送请求失败,ex:{0}", ex));

                return string.Empty;
            }
        }
    }
}
